// packageFT/guide/add-added-fee/add-added-fee.js
const app = getApp()
import { debounce } from '../../../utils/util'
const generateUniqueID = function() {
  const timestamp = Date.now().toString(36);
  const uniqueRandom = Math.random().toString(36).substr(2, 9);
  return `_${timestamp}${uniqueRandom}`;
}
/**
 * 保留小数点后N位小数
 * @param value string 需要转换的值
 * @param digit number 小数点位数， 默认保留两位小数
 * @returns
 */
const formatPrice = function(value, digit) {
  const reg = new RegExp(`^(\-)\*(\\d+)\\.((\\d){${digit}})\.\*$`)
  value = value
    .replace(/[^\d.]/g, '')
    .replace(/\.{2,}/g, '.')
    .replace(/^(0(0)+|\.)/g, '')
    .replace('.', '$#$')
    .replace(/\./g, '')
    .replace('$#$', '.')
    .replace(reg, '$1$2.$3')
    // .replace(/^(-)*(\d+)\.((\d){8}).*$/, '$1$2.$3')
  return value
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    feeList: [],
    loading: false,
    oid: 0,
    total: 0,
    timer: null
  },

  /**
   * 初始化列表数据
   */
  initList: function() {
    let list = [...this.data.feeList]
    if (list.length) {
      list.forEach(item => {
        if (!item.uniqueID) {
          item.uniqueID = generateUniqueID()
        }
      })
    } else {
      list.push({
        uniqueID: generateUniqueID(),
        name: '',
        price: ''
      })
    }
    this.setData({ feeList: list })
    this.getTotal()
  },

  /**
   * 增值项输入
   * @param {Objexct} e 
   */
  nameChange: function(e) {
    const inputValue = e.detail
    const { index } = e.currentTarget.dataset
    const key = `feeList[${index}].name`
    this.setData({
      [key]: inputValue
    })
  },

  /**
   * 价格格式化，只能输入数值，含小数
   * @param {Object} e 
   */
  priceChange: function(e) {
    const inputValue = e.detail
    const { index } = e.currentTarget.dataset
    const key = `feeList[${index}].price`
    this.setData({
      [key]: formatPrice(inputValue, 2)
    })
    // 防抖
    if (this.timer) clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      debounce(this.getTotal())
    }, 1000);
  },

  /**
   * 计算总价
   */
  getTotal: function() {
    const { feeList } = this.data
    const money = feeList.reduce(function(total, item) {
      const addend = Boolean(parseFloat(item.price)) ? parseFloat(item.price) : 0
      return total + addend
    }, 0)
    this.setData({ total: money.toFixed(2)})
  },

  /**
   * 添加/删除费用项
   * @param {Object} e 
   */
  operateItem: function(e) {
    const { index, type } = e.currentTarget.dataset
    let list = [...this.data.feeList]
    // 添加项
    if (type == 'add') {
      if (list.length == 10) {
        app.tips('最多添加10项！')
        return
      }
      // 执行添加
      list.splice(index + 1, 0, {
        uniqueID: generateUniqueID(),
        name: '',
        price: ''
      })
    } 
    // 删除项
    else if(type == 'del') {
      // 仅剩一条禁止删除
      if (list.length == 1) {
        app.tips('至少保留1项！')
        return
      }
      // 删除
      list.splice(index, 1)
    }
    this.setData({ feeList: list })
    // 增值项删除，重新计算总价
    if (type == 'del') {
      this.getTotal()
    }
  },

  /**
   * 提交前检查
   */
  submitCheck: function() {
    const list = [...this.data.feeList]
    // 筛选未填写完整的项
    const incompleteList = list.filter(item => app._isTextEmpty(item.name) || app._isTextEmpty(item.price))
    // 是否所有项都未填写完整
    if (incompleteList.length == list.length) {
      app.tips('无完整数据可提交！')
      return
    }
    // 存在未填写完整的数据，给出提示是否继续提交
    if (incompleteList.length) {
      const _this = this
      wx.showModal({
        title: '提示',
        content: '有未填写完整的增值项，继续提交将忽略这些数据，是否确认提交',
        cancelText: '返回检查',
        confirmText: '确认提交',
        complete: (res) => {
          if (res.confirm) {
            // 筛选出填写完整的项继续提交
            const completeList = list.filter(item => !incompleteList.some(obj => obj.uniqueID == item.uniqueID))
            _this.doSubmit(completeList)
          }
        }
      })
    } else {
      this.doSubmit(list)
    }
  },

  /**
   * 提交
   * @param {Array} list 输入完整的列表
   */
  doSubmit: function(list) {
    console.log(list)
    const { oid } = this.data
    if(!oid) return
    const urlStr = app.getNetAddresss('plugin.guide.frontend.need-order-operate.store-surcharge')
    const data = {
      order_id :oid,
      options: list
    }
    const _this = this
    this.setData({ loading: true })
    wx.showLoading({ title: '加载中...' })
    app._postNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.showModal({
            title: '成功',
            content: '增值项添加成功',
            showCancel: false,
            complete: (res) => {
              if (res.confirm) {
                const pages = getCurrentPages()
                //获取上一个页面的实例
                const beforePage = pages[pages.length - 2]
                //1、调用上一个页面onLoad
                beforePage.onLoad({ oid }) 
                //2、调用上一个页面刷新方法
                beforePage.getDetail()
                wx.navigateBack({ delta: -1 })
              }
            }
          })
        } else {
          app.tips(resData.msg || '请求失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
        _this.setData({ loading: false })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let feeList = []
    let oid = 0
    const { params } = options
    if (params) {
      const eParams = JSON.parse(decodeURIComponent(params))
      feeList = eParams.list
      oid = eParams.oid
    }
    this.setData({ oid, feeList})
    this.initList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})